package com.wxdc.nmgyt.nmgytwydc.fragment;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.esri.android.map.GraphicsLayer;
import com.esri.android.map.Layer;
import com.esri.android.map.LocationDisplayManager;
import com.esri.android.map.MapView;
import com.esri.android.map.ags.ArcGISLocalTiledLayer;
import com.esri.android.map.event.OnSingleTapListener;
import com.esri.android.map.event.OnStatusChangedListener;
import com.esri.android.runtime.ArcGISRuntime;
import com.esri.core.geometry.Geometry;
import com.esri.core.geometry.GeometryEngine;
import com.esri.core.geometry.Line;
import com.esri.core.geometry.Point;
import com.esri.core.geometry.Polygon;
import com.esri.core.geometry.Polyline;
import com.esri.core.geometry.SpatialReference;
import com.esri.core.map.Graphic;
import com.esri.core.symbol.FillSymbol;
import com.esri.core.symbol.PictureMarkerSymbol;
import com.esri.core.symbol.SimpleFillSymbol;
import com.esri.core.symbol.SimpleLineSymbol;
import com.esri.core.symbol.TextSymbol;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.wxdc.nmgyt.nmgytwydc.IMapFunInterface.IMapFunInterface;
import com.wxdc.nmgyt.nmgytwydc.R;
import com.wxdc.nmgyt.nmgytwydc.app.MyApp;
import com.wxdc.nmgyt.nmgytwydc.common.CoordinateConvert;
import com.wxdc.nmgyt.nmgytwydc.utils.FileUtil;
import com.wxdc.nmgyt.nmgytwydc.utils.SaveGpsDataUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import it.beppi.tristatetogglebutton_library.TriStateToggleButton;

/**
 * Created by Administrator on 2018/3/23.
 * Arcgis离线地图
 */

public class LocalArcgisMapFragment extends Fragment {
    Unbinder unbinder;
    private final String TAG = this.getClass().getSimpleName();
    @BindView(R.id.baidu_loc_btn)
    ImageButton mBaiduLocBtn;
    @BindView(R.id.baidu_imageBtn_getGps)
    ImageButton mBaiduImageBtnGetGps;
    @BindView(R.id.baidu_imageBtn_saveGpsData)
    ImageButton mBaiduImageBtnSaveGpsData;
    @BindView(R.id.map_gps_value_relativeLayout)
    RelativeLayout mMapGpsValueRelativeLayout;
    @BindView(R.id.map_tools_tstb_btn)
    TriStateToggleButton mMapToolsTstbBtn;
    @BindView(R.id.map_tools_tstb_txthint)
    TextView mMapToolsTstbTxthint;
    @BindView(R.id.map_tools_togBtn_LinearLayout)
    LinearLayout mMapToolsTogBtnLinearLayout;
    @BindView(R.id.map_tools_imageBtn_mark)
    ImageButton mMapToolsImageBtnMark;
    @BindView(R.id.map_tools_imageBtn_txtmark)
    TextView mMapToolsImageBtnTxtmark;
    @BindView(R.id.map_tools_imageBtn_distance)
    ImageButton mMapToolsImageBtnDistance;
    @BindView(R.id.map_tools_imageBtn_txtdistance)
    TextView mMapToolsImageBtnTxtdistance;
    @BindView(R.id.map_tools_imageBtn_area)
    ImageButton mMapToolsImageBtnArea;
    @BindView(R.id.map_tools_imageBtn_txtarea)
    TextView mMapToolsImageBtnTxtarea;
    @BindView(R.id.map_tools_imageBtn_linnearLayout)
    LinearLayout mMapToolsImageBtnLinnearLayout;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.toolbar_title)
    TextView mToolbarTitle;
    private MapView mMapView;
    private Location mLocation;
    private MyApp mApp;
    private LocationListener mListener;
    private String mapImageFolderPath;//影像文件夹路径
    private String mapLayerFolderPath;//图层文件夹路径
    private RxPermissions rxPermissions;
    private int mapToolsFlag = 0;//默认0:不操作；1：标记；2:测距离；3：测面积
    private int measureWay = 0;// 1:触摸获得点信息测量；2：GPS获得点测量
    private AppCompatActivity mActivity;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mActivity = (AppCompatActivity) context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "onCreate: ---------------------");
        mApp = MyApp.getInstance();
        mapImageFolderPath = FileUtil.filePath + FileUtil.MapImageFile;
        mapLayerFolderPath = FileUtil.filePath + FileUtil.MapLayerFile;
        rxPermissions = new RxPermissions(mActivity);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.i(TAG, "onCreateView: -----------------------");
        View view = inflater.inflate(R.layout.fragment_localarcgismap, container, false);
        unbinder = ButterKnife.bind(this, view);
        setHasOptionsMenu(true);//想让Fragment中的onCreateOptionsMenu生效必须先调用setHasOptionsMenu方法
        mActivity.setSupportActionBar(mToolbar);
        mActivity.getSupportActionBar().setTitle("");
        mToolbarTitle.setText(R.string.main_toolbar_title_localmap);
        mMapView = view.findViewById(R.id.local_mapview);
        mMapView.setEsriLogoVisible(false);
        ArcGISRuntime.setClientId("9yNxBahuPiGPbsdi");//去水印
        mMapView.enableWrapAround(false);//启用或禁用地图环绕功能
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mMapView.setOnStatusChangedListener(new OnStatusChangedListener() {
            @Override
            public void onStatusChanged(Object o, STATUS status) {
                if (status == STATUS.INITIALIZED) {
                    if (mActivity instanceof IMapFunInterface) {
                        mLocation =  ((IMapFunInterface) mActivity).getLocation();
                    }
                    initLocalPosition();
                    Log.i(TAG, "onStatusChanged: -------------" + mLocation);
                    if (mLocation != null) {
                        mMapView.centerAt(mLocation.getLatitude(), mLocation.getLongitude(), true);
                    }

                }
            }
        });
        mMapToolsTstbBtn.setOnToggleChanged(new TriStateToggleButton.OnToggleChanged() {
            @Override
            public void onToggle(TriStateToggleButton.ToggleStatus toggleStatus, boolean b, int i) {
                switch (toggleStatus) {
                    case off:
                        mMapToolsImageBtnLinnearLayout.setVisibility(View.GONE);
                        mMapGpsValueRelativeLayout.setVisibility(View.GONE);
                        mMapToolsTstbTxthint.setText("");
                        mMapToolsImageBtnTxtmark.setTextColor(getResources().getColor(R.color.white));
                        mMapToolsImageBtnTxtdistance.setTextColor(getResources().getColor(R.color.white));
                        mMapToolsImageBtnTxtarea.setTextColor(getResources().getColor(R.color.white));
                        measureWay = 0;
                        mapToolsFlag = 0;
                        checkedMapToolsGraphicsLayerIsExist();
                        break;
                    case mid:
                        mMapToolsImageBtnLinnearLayout.setVisibility(View.VISIBLE);
                        mMapToolsTstbTxthint.setText("touch");
                        measureWay = 1;
                        map_tools_graphicslayer = new GraphicsLayer();
                        map_tools_graphicslayerID = map_tools_graphicslayer.getID();
                        mMapView.addLayer(map_tools_graphicslayer);
                        break;
                    case on:
                        mMapGpsValueRelativeLayout.setVisibility(View.VISIBLE);
                        mMapToolsTstbTxthint.setText("gps");
                        if (gpsPoints == null) {
                            gpsPoints = new ArrayList<>();
                        }
                        firstRecord = true;
                        gpsPoints.clear();
                        measureWay = 2;
                        map_tools_graphicslayer.removeAll();
                        break;
                }
            }
        });
        mMapView.setOnSingleTapListener(new OnSingleTapListener() {
            @Override
            public void onSingleTap(float screenX, float screenY) {
                Point point = mMapView.toMapPoint(screenX, screenY);
                if (measureWay == 1) {
                    switch (mapToolsFlag) {
                        case 1://标记点
                            drawType = Geometry.Type.POINT;
                            mPictureMarkerSymbol = new PictureMarkerSymbol(getResources().getDrawable(R.mipmap.map_tool_point));
                            drawcoordGeometry(point);
                            Log.i(TAG, "onSingleTap: -------------------marker");
                            break;
                        case 2://测距离
                            drawType = Geometry.Type.POLYLINE;
                            mLineSymbol = new SimpleLineSymbol(getResources().getColor(R.color.lime), 2.0f, SimpleLineSymbol.STYLE.SOLID);
                            drawcoordGeometry(point);
                            break;
                        case 3://测面积
                            drawType = Geometry.Type.POLYGON;
                            mFillSymbol = new SimpleFillSymbol(getResources().getColor(R.color.lime), SimpleFillSymbol.STYLE.SOLID);
                            mFillSymbol.setAlpha(50);
                            drawcoordGeometry(point);
                            break;
                    }
                }
            }
        });
    }
    /*
    * 添加菜单
    * */

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
        inflater.inflate(R.menu.arcgis_local_fragment_menu, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }
    /*
    * 菜单选中事件
    * */

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int selectID = item.getItemId();
        switch (selectID) {
            case R.id.af_menu_item_onlineMap:
                if (mActivity instanceof IMapFunInterface) {
                    ((IMapFunInterface) mActivity).switchMap("baiduMap");
                }
                break;
            case R.id.af_menu_item_localMap:
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /*
    * 按钮点击事件
    * */
    @OnClick({R.id.baidu_loc_btn, R.id.baidu_imageBtn_getGps, R.id.baidu_imageBtn_saveGpsData, R.id.gisMap_imagBtn_zoomOut, R.id.gisMap_imagBtn_zoomIn, R.id.gisMap_imagBtn_image, R.id.gisMap_imagBtn_layer, R.id.map_tools_imageBtn_mark, R.id.map_tools_imageBtn_distance, R.id.map_tools_imageBtn_area})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.baidu_loc_btn:// 定位当前位置
                mApp.checkLocaltionPermissions(mActivity);
                mLocation =  ((IMapFunInterface) mActivity).getLocation();
                if (mLocation == null) {
                    mApp.showToastShortMessage(mActivity, "无法获取定位信息，请检查GPS是否打开");
                    return;
                }
                mMapView.centerAt(mLocation.getLatitude(), mLocation.getLongitude(), true);
                break;
            case R.id.baidu_imageBtn_getGps://gps设点
                rxPermissions.request(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
                        .subscribe(granted -> {
                            if (granted) {
                                userGpsMeasure();
                            }
                        });
                break;
            case R.id.baidu_imageBtn_saveGpsData://保存gps数据
                Log.i(TAG, "onViewClicked: --------------" + gpsPoints.size());
                rxPermissions.request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(granted -> {
                            if (granted) {
                                // All requested permissions are granted
                                SaveGpsDataUtil gpsDataUtil = new SaveGpsDataUtil(mActivity);
                                gpsDataUtil.saveGpsDataInfoByGis(gpsPoints, map_tools_graphicslayer);
                            }
                        });

                break;
            case R.id.gisMap_imagBtn_zoomOut://地图放大
                mMapView.zoomout(true);
                break;
            case R.id.gisMap_imagBtn_zoomIn://地图缩小
                mMapView.zoomin(true);
                break;
            case R.id.gisMap_imagBtn_image://加载离线影像图
                rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                        .subscribe(granted -> {
                            if (granted) {
                                checkedCurrentLocalImageIsExist();
                                showImageDataDialog();
                            }
                        });

                break;
            case R.id.gisMap_imagBtn_layer://加载离线矢量图
                rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                        .subscribe(granted -> {
                            if (granted) {
                                checkedMapLayerIsLoaded();
                                showLayerDataDialog();
                            }
                        });
                break;
            case R.id.map_tools_imageBtn_mark://标记
                mMapToolsImageBtnTxtmark.setTextColor(getResources().getColor(R.color.red));
                mMapToolsImageBtnTxtdistance.setTextColor(getResources().getColor(R.color.white));
                mMapToolsImageBtnTxtarea.setTextColor(getResources().getColor(R.color.white));
                mapToolsFlag = 1;
                firstRecord = true;
                map_tools_graphicslayer.removeAll();
                if (measureWay == 2) {
                    gpsPoints.clear();
                }
                break;
            case R.id.map_tools_imageBtn_distance://测距离
                mMapToolsImageBtnTxtdistance.setTextColor(getResources().getColor(R.color.red));
                mMapToolsImageBtnTxtarea.setTextColor(getResources().getColor(R.color.white));
                mMapToolsImageBtnTxtmark.setTextColor(getResources().getColor(R.color.white));
                mapToolsFlag = 2;
                firstRecord = true;
                map_tools_graphicslayer.removeAll();
                if (measureWay == 2) {
                    gpsPoints.clear();
                }
                break;
            case R.id.map_tools_imageBtn_area://测面积
                mMapToolsImageBtnTxtarea.setTextColor(getResources().getColor(R.color.red));
                mMapToolsImageBtnTxtmark.setTextColor(getResources().getColor(R.color.white));
                mMapToolsImageBtnTxtdistance.setTextColor(getResources().getColor(R.color.white));
                mapToolsFlag = 3;
                firstRecord = true;
                map_tools_graphicslayer.removeAll();
                if (measureWay == 2) {
                    gpsPoints.clear();
                }
                break;
        }
    }

    /*
    * 初始化定位方法
    * */
    private LocationDisplayManager mDisplayManager;

    private void initLocalPosition() {
        if (mDisplayManager == null) {
            mDisplayManager = mMapView.getLocationDisplayManager();
        }
        mDisplayManager.setAccuracyCircleOn(true);
        mDisplayManager.setAllowNetworkLocation(true);
        mDisplayManager.setAutoPanMode(LocationDisplayManager.AutoPanMode.LOCATION);
        mDisplayManager.setShowPings(true);
        if (mActivity instanceof IMapFunInterface) {
            mListener =  ((IMapFunInterface) mActivity).getLocationListener();
        }
        mDisplayManager.setLocationListener(mListener);
        try {
            mDisplayManager.setAccuracySymbol(new SimpleFillSymbol(getResources().getColor(R.color.skyblue), SimpleFillSymbol.STYLE.SOLID).setAlpha(90));
            mDisplayManager.setDefaultSymbol(new PictureMarkerSymbol(this.getResources().getDrawable(R.drawable.arrow)));
            mDisplayManager.setLocationAcquiringSymbol(new PictureMarkerSymbol(getResources().getDrawable(R.drawable.arrow)));
            mDisplayManager.setLocationFilterCallback(new LocationDisplayManager.LocationFilterCallback() {
                @Override
                public boolean canApplyNewLocation(Location location, Location location1) {
                    //Log.i(TAG, "canApplyNewLocation: -------location:"+location+"------location1:"+location1);
                    return false;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (!mDisplayManager.isStarted()) {
            mDisplayManager.start();
            Log.i(TAG, "initLocalPosition: -------------打开定位图层---------"+ CoordinateConvert.getInstance().jwdConvert(106, 14, 15));
        }

    }

    /*
    * 显示影像数据对话框
    * */
    private void showImageDataDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
        builder.setTitle("离线数据(影像或矢量.tpk)");
        File mapImageFolder = FileUtil.createImageFolder();
        final String[] localImgs = mapImageFolder.list();
        builder.setItems(localImgs, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String localImgName = localImgs[i];
                requestLocalMapService(localImgName);
            }
        });
        builder.show();
    }

    /*
    * 显示离线图层对话框
    * */
    private void showLayerDataDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
        builder.setTitle("添加自定义图层");
        File layerFolder = FileUtil.createLayerFolder();
        final String[] localLayers = layerFolder.list();
        builder.setItems(localLayers, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String mapLayerName = localLayers[i];
                requestMapLayer(mapLayerName);
            }
        });
        builder.show();

    }

    /*
   * 加载本地离线地图(离线影像图).tpk文件
   * */
    private ArcGISLocalTiledLayer localTiledImgLayer;
    private Long localTiledImgLayerID = 0l;

    private void checkedCurrentLocalImageIsExist() {//检查当前离线影像图层是否存在。存在：移除
        Layer preLocalTiledImgLayer = mMapView.getLayerByID(localTiledImgLayerID);
        if (preLocalTiledImgLayer != null) {
            mMapView.removeLayer(preLocalTiledImgLayer);
        }
    }

    private void requestLocalMapService(String imageName) {
        localTiledImgLayer = new ArcGISLocalTiledLayer(mapImageFolderPath + "/" + imageName);
        localTiledImgLayerID = localTiledImgLayer.getID();
        mMapView.addLayer(localTiledImgLayer);
        if (mLocation != null) {
            mMapView.centerAt(mLocation.getLatitude(), mLocation.getLongitude(), true);
        }
    }

    /*
    * 加载离线图层 .tpk文件
    * */
    private ArcGISLocalTiledLayer mapLayer;
    private Long mapLayerID = 0l;

    private void checkedMapLayerIsLoaded() {//检查是否已经加载图层
        Layer preMapLayer = mMapView.getLayerByID(mapLayerID);
        if (preMapLayer != null) {
            mMapView.removeLayer(preMapLayer);
        }
    }

    private void requestMapLayer(String layerName) {
        mapLayer = new ArcGISLocalTiledLayer(mapLayerFolderPath + "/" + layerName);
        mapLayerID = mapLayer.getID();
        mMapView.addLayer(mapLayer);
        if (mLocation != null) {
            mMapView.centerAt(mLocation.getLatitude(), mLocation.getLongitude(), true);
        }
    }

    /*
    * 检查map_tools_graphicslayer 是否添加到mapview
    * */
    private Long map_tools_graphicslayerID = 0l;

    private void checkedMapToolsGraphicsLayerIsExist() {
        map_tools_graphicslayer = (GraphicsLayer) mMapView.getLayerByID(map_tools_graphicslayerID);
        if (map_tools_graphicslayer != null) {
            mMapView.removeLayer(map_tools_graphicslayer);
        }
    }

    /*
    * 利用GPS测量
    * */
    private List<Point> gpsPoints;

    private void userGpsMeasure() {
        if (mLocation == null) {
            mApp.showToastLongMessage(mActivity, "GPS点获得失败");
            return;
        }
        Point point = new Point(mLocation.getLongitude(), mLocation.getLatitude());
        gpsPoints.add(point);
        if (measureWay == 2) {//测量方式
            switch (mapToolsFlag) {
                case 1://标记
                    drawType = Geometry.Type.POINT;
                    mPictureMarkerSymbol = new PictureMarkerSymbol(getResources().getDrawable(R.mipmap.map_tool_point));
                    drawcoordGeometry(point);
                    break;
                case 2://测距离
                    drawType = Geometry.Type.POLYLINE;
                    mLineSymbol = new SimpleLineSymbol(getResources().getColor(R.color.lime), 2.0f, SimpleLineSymbol.STYLE.SOLID);
                    drawcoordGeometry(point);
                    break;
                case 3://测面积
                    drawType = Geometry.Type.POLYGON;
                    mFillSymbol = new SimpleFillSymbol(getResources().getColor(R.color.lime), SimpleFillSymbol.STYLE.SOLID);
                    mFillSymbol.setAlpha(50);
                    drawcoordGeometry(point);
                    break;
            }
        }
    }

    /*
    *画点、线、面
    * */
    //  设定绘制的类型
    private SimpleLineSymbol mLineSymbol;
    private SimpleFillSymbol mFillSymbol;
    private PictureMarkerSymbol mPictureMarkerSymbol;
    private Point ptStart;
    private Point ptPrevious;
    private Polygon polygon;
    double totalLength = 0;
    int pointNum = 0;//用于控制多边形周长计算
    private int PolygonUid, PolygonTextUid;
    private Geometry.Type drawType;
    private GraphicsLayer map_tools_graphicslayer;
    private boolean firstRecord;

    private void drawcoordGeometry(Point point) {
        if (firstRecord) {
            ptPrevious = null;
            ptStart = null;
            polygon = null;
            totalLength = 0;
            pointNum = 0;
        }
        Point ptCurrent;
        if (measureWay == 1) {
            ptCurrent = point;
        } else {
            ptCurrent = (Point) GeometryEngine.project(point, SpatialReference.create(SpatialReference.WKID_WGS84), mMapView.getSpatialReference());
        }
        if (drawType == Geometry.Type.POINT) {
            Graphic pGraphic = new Graphic(ptCurrent, mPictureMarkerSymbol);
            map_tools_graphicslayer.addGraphic(pGraphic);
        } else {
            pointNum++;
            if (ptStart == null) {
                ptStart = ptCurrent;
                // Graphic pgraphic = new Graphic(ptStart, new SimpleMarkerSymbol(Color.RED, 8, SimpleMarkerSymbol.STYLE.CIRCLE));
                Graphic pgraphic = new Graphic(ptStart, new PictureMarkerSymbol(getResources().getDrawable(R.mipmap.map_tool_point)));
                map_tools_graphicslayer.addGraphic(pgraphic);
            } else {
                //Graphic pGraphic = new Graphic(ptCurrent, new SimpleMarkerSymbol(Color.RED, 8, SimpleMarkerSymbol.STYLE.CIRCLE));
                Graphic pGraphic = new Graphic(ptCurrent, new PictureMarkerSymbol(getResources().getDrawable(R.mipmap.map_tool_point)));
                map_tools_graphicslayer.addGraphic(pGraphic);
                Line line = new Line();
                line.setStart(ptPrevious);
                line.setEnd(ptCurrent);
                totalLength += line.calculateLength2D();
                if (drawType == Geometry.Type.POLYLINE) {
                    Polyline polyline = new Polyline();
                    polyline.addSegment(line, true);
                    Graphic iGraphicSymbol = new Graphic(polyline, mLineSymbol);
                    map_tools_graphicslayer.addGraphic(iGraphicSymbol);
                    TextSymbol textSymbol = new TextSymbol(14, String.format("%.2f", line.calculateLength2D()) + "m | " + String.format("%.2f", totalLength) + "m", Color.RED);
                    Graphic txtGraphic = new Graphic(ptCurrent, textSymbol);
                    map_tools_graphicslayer.addGraphic(txtGraphic);
                } else if (drawType == Geometry.Type.POLYGON) {
                    if (polygon == null) {
                        polygon = new Polygon();
                    }
                    polygon.addSegment(line, false);
                    //多边形周长 polygon.calculateLength2D() ;多边形面积：polygon.calculateArea2D()
                    TextSymbol polygonTextSymbol = new TextSymbol(14, String.format("%.2f", polygon.calculateLength2D()) + " m | " + String.format("%.2f", Math.abs(polygon.calculateArea2D())) + " m2", Color.RED);
                    Graphic gGraphic = new Graphic(polygon, mFillSymbol);
                    map_tools_graphicslayer.removeGraphic(PolygonUid);
                    map_tools_graphicslayer.removeGraphic(PolygonTextUid);
                    PolygonUid = map_tools_graphicslayer.addGraphic(gGraphic);
                    PolygonTextUid = map_tools_graphicslayer.addGraphic(new Graphic(ptCurrent, polygonTextSymbol));
                }
            }
        }
        //writeFile(wgspoint.getX()+"<------>"+wgspoint.getY()+"         "+currtDateTime()+"\r\n");
        //TempData.pointList.add(new LatLng(wgspoint.getY(), wgspoint.getX()));
        ptPrevious = ptCurrent;
        firstRecord = false;
    }




    /*生命周期*/

    @Override
    public void onStart() {
        super.onStart();
        Log.i(TAG, "onStart: --------------");
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.unpause();
        Log.i(TAG, "onResume: ---------------");
        if (mDisplayManager != null) {
            mDisplayManager.resume();
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.pause();
        if (mDisplayManager != null) {
            mDisplayManager.pause();
        }
        Log.i(TAG, "onPause: --------------------");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.i(TAG, "onStop: -------------------");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        Log.i(TAG, "onDestroyView: ------------------"+mDisplayManager);
        if (mDisplayManager != null) {
            mDisplayManager.stop();
            mDisplayManager = null;
            Log.i(TAG, "onDestroyView: -------关闭定位图层----------");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Release MapView resources
        mMapView.recycle();
        mMapView = null;
        Log.i(TAG, "onDestroy: --------------------");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.i(TAG, "onDetach: ------------------------");
        mActivity = null;
    }


}
